import config
import requests
import logging

from flask import  request,Blueprint,request

from applications.functions.response import success_response,error_response
from applications.functions.novel_data import novel_search_data,novel_book_data,novel_toc_data,novel_content_data


from urllib.parse import quote_plus 

app = config.anime_app
siwa = config.anime_siwa
siwa_tag = "小说相关操作"
group_name = "小说搜索"

novel = Blueprint('novel',__name__)

@novel.route('/api/novel/search', methods=['GET'])
@siwa.doc(tags=[siwa_tag], group=group_name)
def novel_search():
    keyword = request.args.get('keyword', '')
    if not keyword:
        return error_response(400, "参数keyword缺失")
    
    try:
        encoded_keyword = quote_plus(keyword)  # 确保从urllib.parse导入
    except Exception as e:  # 添加编码异常处理
        logging.error(f"URL编码失败: {str(e)}")
        return error_response(500, "关键词编码错误")
    
    base_url = "https://www.biquuge.com"
    search_url = f"{base_url}/search.php?q={encoded_keyword}"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "Referer": f"{base_url}/"
    }
    
    try:
        response = requests.get(search_url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查HTTP错误
        
        novels = novel_search_data(response.text)

        return success_response(200, "搜索成功", novels["data"])
        
    except requests.exceptions.RequestException as e:
        error_msg = f"网络请求失败: {str(e)}"
        logging.error(f"{error_msg} URL={search_url}")
        return error_response(502, error_msg)
    except Exception as e:
        logging.exception(f"数据处理异常: {str(e)}")  # 记录完整堆栈
        return error_response(500, "服务器处理错误")

@novel.route('/api/novel/book', methods=['GET'])
@siwa.doc(tags=[siwa_tag], group=group_name)
def book():
    # 1. 获取并验证comicUrl参数
    book_url = request.args.get('url')
    if not book_url:
        return error_response(400, "参数bookUrl缺失")
    try:
        # 2. 配置请求头(防反爬)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "Referer": "https://www.biquuge.com/"
        }
        
        # 3. 获取目标网页内容
        response = requests.get(book_url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查HTTP状态码
        book = novel_book_data(response.text)
        return success_response(200, "获取成功", book["data"])

    except requests.exceptions.RequestException as e:
        error_msg = f"网络请求失败: {str(e)}"
        logging.error(f"{error_msg} URL={book_url}")
        return error_response(502, error_msg)
    except Exception as e:
        logging.exception(f"数据处理异常: {str(e)}")  # 记录完整堆栈
        return error_response(500, "服务器处理错误")

@novel.route('/api/novel/toc', methods=['GET'])
@siwa.doc(tags=[siwa_tag], group=group_name)
def toc():
    # 1. 获取并验证comicUrl参数
    toc_url = request.args.get('url')
    if not toc_url:
        return error_response(400, "参数tocUrl缺失")
    try:
        # 2. 配置请求头(防反爬)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "Referer": "https://www.biquuge.com/"
        }
        
        # 3. 获取目标网页内容
        response = requests.get(toc_url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查HTTP状态码
        book = novel_toc_data(response.text)
        return success_response(200, "获取成功", book["data"])

    except requests.exceptions.RequestException as e:
        error_msg = f"网络请求失败: {str(e)}"
        logging.error(f"{error_msg} URL={comic_url}")
        return error_response(502, error_msg)
    except Exception as e:
        logging.exception(f"数据处理异常: {str(e)}")  # 记录完整堆栈
        return error_response(500, "服务器处理错误")

@novel.route('/api/novel/content', methods=['GET'])
@siwa.doc(tags=[siwa_tag], group=group_name)
def content():
    # 1. 获取并验证comicUrl参数
    content_url = request.args.get('url')
    print(content_url)
    if not content_url:
        return error_response(400, "参数contentUrl缺失")
    try:
        # 2. 配置请求头(防反爬)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "Referer": "https://www.biquuge.com/"
        }
        
        # 3. 获取目标网页内容
        response = requests.get(content_url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查HTTP状态码
        content = novel_content_data(response.text)

        return success_response(200, "获取成功", content)

    except requests.exceptions.RequestException as e:
        error_msg = f"网络请求失败: {str(e)}"
        logging.error(f"{error_msg} URL={content_url}")
        return error_response(502, error_msg)
    except Exception as e:
        logging.exception(f"数据处理异常: {str(e)}")  # 记录完整堆栈
        return error_response(500, "服务器处理错误")